package day7.timer.impl2;

import java.util.concurrent.PriorityBlockingQueue;

public class Worker extends Thread {
    private final PriorityBlockingQueue<MyTimerTask> queue;

    Worker(PriorityBlockingQueue<MyTimerTask> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true) {
            MyTimerTask task = null;
            try {
                task = queue.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // task 应该有个应该执行的时刻（不能记录 delay）
            long now = System.currentTimeMillis();
            long delay = task.runAt - now;
            if (delay <= 0) {
                task.run();
            } else {
                try {
                    Thread.sleep(delay);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                task.run();
            }
        }
    }
}
